<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" style="--el-dialog-width:75%">
    <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
        :inline="true"
    >
      <el-form-item label="归属项目" prop="belongingProject">
        <!--          <el-input v-model="row.belongingProject" placeholder="请输入归属项目"/>-->
        <el-select
            v-model="formData.belongingProject"
            placeholder="请选择归属项目"
            filterable
            @focus="remoteMethod"
            class="!w-240px"
        >
          <el-option
              v-for="item in options"
              :key="item.projectName"
              :label="item.projectName"
              :value="item.projectName"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-select
            v-model="formData.type"
            placeholder="请选择物资分类"
            clearable
            class="!w-240px"
        >
          <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.ERP_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据日期" prop="documentDate">
        <el-date-picker
            v-model="documentNumberDateA"
            type="datetime"
            placeholder="单据日期"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="MMM DD, YYYY"
            time-format="HH:mm"
        />
      </el-form-item>

      <el-form-item label="单据编号" prop="documentNumber">
        <el-input v-model="formData.documentNumber" style="width: 240px" placeholder="单据编号"
        />
      </el-form-item>

    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="项目物资申请单" name="projectOrder">
        <ProjectOrderForm
ref="projectOrderFormRef" :documentNumber="formData.documentNumber"
                          :type="props.typeP" />
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {MaterialDemandApi, MaterialDemandVO} from '@/api/werp/purchase/materialdemand'
import ProjectOrderForm from './components/ProjectOrderForm.vue'
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import {ref} from "vue";
import {PojectInfoApi, PojectInfoVO} from "@/api/material/pojectinfo";
import { number } from 'vue-types';

const props = defineProps<{
  typeP: String;
  documentNumberDateA: '';
  documentNumber: {
    type: String|undefined, // 确保类型
    required: true,
  },
}>();

let documentNumberDateA = ref(props.documentNumberDateA);

let options = ref<PojectInfoVO[]>([])
/** 单据 表单 */
defineOptions({name: 'MaterialDemandForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
let formData = ref({
  type: number,
  belongingProject: undefined, // 归属项目id
  id: undefined,
  documentNumber: String,
  documentDate: '',
})
const formRules = reactive({})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('projectOrder')
const projectOrderFormRef = ref()


/** 打开弹窗 */
const open = async (type: string, id?: number) => {

  dialogVisible.value = true
 
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      // 获取数据
      const data = await MaterialDemandApi.getMaterialDemand(id)
      console.log("formData.value1234", formData.value.documentNumber)
      formData.value = data;
      documentNumberDateA.value = data.documentDate ;
      formData.value.type=Number(data.type);
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  
  // 校验表单
  await formRef.value.validate()
  // 校验子表单

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MaterialDemandVO
    console.log("type", formData.value.type )

    // 拼接子表的数据
    data.projectOrders = projectOrderFormRef.value.getData().map(item => {
      item.id = null;  // 将每个对象的 id 设置为 null
      return item;     // 返回修改后的对象
    });
    data.documentDate = documentNumberDateA.value as any
    // data.documentDate = value1.value as any
    // data.documentNumber = documentNumberZ.value as any
    if (formType.value === 'create') {
      await MaterialDemandApi.createMaterialDemand(data)
      message.success(t('common.createSuccess'))
    } else {
      await MaterialDemandApi.updateMaterialDemand(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    type: undefined,
    belongingProject: undefined,
    id: undefined,
    documentNumber: String,
    documentDate: '',
  }

  formRef.value?.resetFields()
}


const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  projectName: undefined,
  phone: undefined,
  createTime: [],
  head: undefined,
})

const remoteMethod = async (query: string) => {
 
  if (query) {
    console.log("queryabc", query)
    const data = await PojectInfoApi.getPojectInfoPage(queryParams)
    console.log("1", data.list)
    options.value = data.list
  } else {
    options.value = []
  }

}

watch(() => props.documentNumber, (newValue) => {
  // console.log("formData.documentDate ", formData.documentDate )
  if (newValue) {
    formData.value.documentNumber =newValue as any;
  }
});

watch(() => props.documentNumberDateA, (newValue) => {
  if (newValue) {
    formData.value.documentDate = newValue;
  }
});


</script>

<style scoped>

</style>

